//index.js
//获取应用实例
const app = getApp()
var utilPay = require('../../utils/beePay.js');
Page({
  data: {
   
    userInfo: {},
    openid :"",
    shop_no:"",
    secret:"",
    appid:"wx113f2407af0ed4da",
    outTradeNo:"",
    totalAmount:0
     
  },
  onShow:function(){
    // console.log("getLaunchOptionsSync.show:", wx.getLaunchOptionsSync());
  },
  onLoad: function (options) {
    var that = this;
    // console.log("getLaunchOptionsSync:",wx.getLaunchOptionsSync());
    for (var i in options){
      this.data[i] = options[i]
    }
    var extraData = app.globalData.extraData;
    if (extraData){
      for (var i in extraData) {
        this.data[i] = extraData[i]
      }
    }
    console.log(" this.data:", this.data);
    wx.showLoading();
    wx.login({
      success: function (res) {
        if (res.code) {
          wx.request({
            url: 'https://www.bestsmartbee.com/api/user/getOpendId', //仅为示例
            data: {
              code: res.code,
              appid: that.data.appid
            },
            method: "POST",
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            success: function (res) {
              var resp = res.data;
              if (resp.code!=200){
                app.alert(resp.code);
                   return;
              }
              that.data.openid = resp.data.openid;
              that.pay();
            }
          })
        }else{
            app.alert("登陆失败");
        }
      }
    })    
  },
  back:function(){

    wx.hideLoading();
    wx.navigateBackMiniProgram({
      extraData: this.data.extraData,
      success(res) {
        // 返回成功
      }
    })
  },
  pay:function(){
    var that = this;
    var shop_no = this.data.shop_no
    var outTradeNo = this.data.outTradeNo ;
    var payinfo = {
      "Method":"PrePay",
      "ShopNo": shop_no,
      "NonceStr": Date.parse(new Date()),
      "OutTradeNo": outTradeNo,
      "TotalAmount": this.data.totalAmount,
      "ChannelType":"WX",
      "OpenId":this.data.openid,
      "SubAppId":this.data.appid,
    };
    this.data.extraData = {
      payinfo: payinfo
    }
    utilPay.beePay({
      "secret": this.data.secret,
      "success":function(res){
          that.data.extraData.error_code = 0;
          that.data.extraData.msg = "succ";
          that.back();
      },
      "fail":function(res){
        that.data.extraData.error_code = 1;
        that.data.extraData.msg = "fail";
        if (res.code && res.code!=0){
          app.alert(res.msg);
          that.data.extraData.msg = res.msg;
        }else{
          that.data.extraData.msg = res.errMsg;
        }
        that.back();
        
      },
      "payinfo": payinfo
    });
    
  }
  
})
